package com.example.streams;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamTest {
    public static void main(String[] args) {
        List<Student> list = getStudentList();
        /**
         * forEach()
         * 1.集合遍历
         */
        list.forEach(System.out::println);

        /**
         * filter(T -> boolean) 保留boolean为true的元素
         *  2.查询高三的同学
         */
        List<Student> list1 = list.stream().filter(student -> student.getGrade().equals("高三")).collect(Collectors.toList());

        /**
         * findFirst() 获取列表中的第一条数据
         * findAny() 找到其中一个元素(stream()第一个元素，parallelStream()找到其中一个元素)
         * 3.查询学生张三的信息
         */
        Student student1 = list.stream().filter(student -> student.getName().equals("张三")).findFirst().orElse(null);

        /**
         * distinct()
         * 4.获取年级信息
         */
        List<String> list2 = list.stream().map(Student::getGrade).distinct().collect(Collectors.toList());

        /**
         * Comparator.comparing(Student::getAge)升序
         * Comparator.comparing(Student::getAge).reversed()降序
         * 5.根据学生年龄排序
         */
        List<Student> list3 = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());

        /**
         * groupingBy() 用于将数据分组，最终返回一个 Map 类型
         * 6.根据年级分组
         */
        Map<String, List<Student>> groupListMap = list.stream().collect(Collectors.groupingBy(Student::getGrade));

    }

    public static List<Student> getStudentList() {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(1, "张三", 16, "高一", "3班"));
        studentList.add(new Student(2, "李四", 18, "高三", "1班"));
        studentList.add(new Student(3, "王五", 16, "高一", "2班"));
        studentList.add(new Student(4, "赵六", 17, "高二", "4班"));
        studentList.add(new Student(5, "马七", 19, "高三", "6班"));
        return studentList;
    }
}
